<?php

namespace app\api\model;

use app\api\model\Cash;
use app\api\model\User;
use think\Cache;
use think\Exception;
use think\Model;
use think\Db;

class Order extends Model
{

    protected $autoWriteTimestamp = true;

    protected $createTime = 'ctime';

    protected $updateTime = 'utime';

    protected $insert = ['ordernumber'];

    protected $dateFormat = 'Y-m-d H:i:s';

    /**
     * @return string
     * @author zhenHong~
     * 设置订单编号
     */
    protected function setOrdernumberAttr()
    {
        return createOrderNumber('ORANGE', 5);
    }


    /**
     * @param $array
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 创建用户订单
     */
    public function createOrder($array)
    {
        //  保养费用 = 支付金额(下单时)
        $num = $this->save($array);
        if ($num) {
            return $this->getOrderInfo($this->ordernumber);
        } else {
            return false;
        }
    }


    /**
     * @param $array
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenhong~
     * 下单支付逻辑
     */
    public function getByOrderNumberSaveInfo($array)
    {
        $data = [
            'name' => $array['name'],
            'phone' => $array['phone'],
            'updooraddress' => $array['updooraddress'] ?: ''
        ];
        $num = self::isUpdate(true)->save($data, ['ordernumber' => $array['ordernumber']]);

        //  若选择了上门取车
        if (array_key_exists('get_car', $array) && $array['get_car'] == 1) {

            //  查询order表订单数据
            $order = self::where(['ordernumber' => $array['ordernumber']])->find();

            //  查询商户 上门取车服务费、违约金
            $cash = new Cash();
            $cashInfo = $cash->where('a_id', $order['a_id'])->field('getcar_nowprice,break_money')->find();

            //  更新 支付金额 和 优惠前金额
            $money = [
                'total_price' => $order['total_price'] + $cashInfo['getcar_nowprice'],
                'pay_price' => $order['pay_price'] + $cashInfo['getcar_nowprice'],
                'discounts_price' => $order['discounts_price'] + $cashInfo['getcar_nowprice']
            ];
            self::save($money, ['id' => $order['id']]);

            //  组装上门取车数据
            $carData = [
                'lon' => $array['lon'],
                'lat' => $array['lat'],
                'r_time' => $array['r_time'],
                'name' => $array['name'],
                'phone' => $array['phone'],
                'address' => $array['address'],
                'money' => $cashInfo['getcar_nowprice'],
                'break_money' => $cashInfo['break_money'],
                'order_id' => $order['id'],
                'order_number' => createOrderNumber('SMQC', 6),
                'u_id' => $order['u_id'],
                'a_id' => $order['a_id'],
            ];
            $carOrder = new Getcarorder();
            $carOrder->save($carData);
        }

        return $num ? true : false;
    }


    /**
     * @param $orderNo
     * @param $openId
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * 支付成功后，回调逻辑
     * 发送模板消息-更新订单-增加商户金钱-插入用户账单-插入商户账单
     */
    public function saveOrderStatusAddUserBill($orderNo, $openId, $wxID)
    {
        //  发送支付成功后的模板消息
        // $prepayId = Cache::get('prepay_id' . $orderNo);
        // if ($prepayId) {
        //     $this->getOrderNoCreateWxMsg($openId, $orderNo, $prepayId);
        // }
        file_put_contents('text1.txt', 1);
        $this->startTrans();
        try {
            // 更新订单状态
            $this->save(['status' => 2, 'transaction_id' => $wxID], ['ordernumber' => $orderNo]);
            file_put_contents('text2.txt', 1);

            //  查询订单
            $info = $this->where('ordernumber', $orderNo)->field('id,pay_type,u_id,c_id,pay_price')->find();
            file_put_contents('text3.txt', 1);

            //  更新商户余额
            $cash = new Cash();
            $cash->where('a_id', $info['c_id'])->setInc('wallet', $info['pay_price']);
            file_put_contents('text4.txt', 1);

            // 组装用户账单数据
            // $userData = [
            //     'u_id' => $info['u_id'],
            //     'a_id' => $info['a_id'],
            //     'price' => $info['pay_price'],
            //     'lessorad' => 1,
            //     'content' => '汽车保养花费' . $info['pay_price'] . '元'
            // ];
            //  组装商户账单数据
            // $cashData = [
            //     'u_id' => $info['u_id'],
            //     'c_id' => $info['c_id'],
            //     'price' => $info['pay_price'],
            //     'lessorad' => 0,
            //     'content' => '用户洗车增加' . $info['pay_price'] . '元'
            // ];

            // //  插入用户账单
            // $userBill = new Userbill();
            // $userBill->save($userData);

            //  插入商户账单
            // $cashBill = new Cashbill();
            // $cashBill->save($cashData);
            // file_put_contents('text5.txt', 1);
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * @param $openId
     * @param $orderNo
     * @param $prepay_id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenhong~
     * 支付成功后给用户推送模板消息
     */
    public function getOrderNoCreateWxMsg($openId, $orderNo, $prepay_id)
    {
        //  预约成功的订单模板ID
        $templateId = 'MvPCfxzwmynKFxvgmzq2-5FnZd-qgNsJGAKgnwl_v0g';
        $orderInfo = $this->getOrderDetailsByOrderNo($orderNo);
        $data = [
            'keyword1' => ['value' => $orderInfo['user_name']],
            'keyword2' => ['value' => $orderInfo['user_phone']],
            'keyword3' => ['value' => $orderInfo['detailed_address']],
            'keyword4' => ['value' => '维修保养'],
            'keyword5' => ['value' => $orderInfo['cash_name']],
            'keyword6' => ['value' => $orderInfo['ordernumber']],
            'keyword7' => ['value' => $orderInfo['goTime']],
            'keyword8' => ['value' => $orderInfo['order_time']]
        ];
        sendWxMessage($openId, $templateId, $data, $prepay_id);
    }


    /**
     * @param $orderId
     * @return array|bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenhong~
     * 用户发起退款操作
     */
    public function checkOrderInfoByOrderID($orderId)
    {
        $back = new BackMoney();
        $backs = $back->where('order_id', $orderId)->field(['ctime', 'utime', 'status'], true)->find();
        if ($backs) {
            $orderInfo = self::where('id', $orderId)->field('u_id,ordernumber')->find();
            return [
                'out_trade_no' => $orderInfo['ordernumber'],
                'total_fee' => $backs['order_money'],
                'refund_fee' => $backs['back_money'],
                'out_refund_no' => $backs['refund_no']
            ];
        } else {
            $order = self::get(function ($query) use ($orderId) {
                $query->where(['id' => $orderId])->field('id,break_scale,ordernumber,maintain_price,pay_price');
            });

            $carOrder = Db::name('Getcarorder')->where('order_id', $orderId)->field('id,money,break_money')->find();

            //  判断服务费 是否存在 且 大于 0
            if ($order['break_scale'] && $order['break_scale'] > 0) {
                $moneyNormal = $order['maintain_price'] * ($order['break_scale'] / 100);
            } else {
                $moneyNormal = $order['maintain_price'];
            }

            //  判断 该订单 是否存在上门取车的订单
            if ($carOrder) {
                if ($carOrder['break_money'] && $carOrder['break_money'] > 0) {
                    $moneyCar = $carOrder['money'] * ($carOrder['break_money'] / 100);
                } else {
                    $moneyCar = $carOrder['money'];
                }
            } else {
                $moneyCar = 0;
            }

            //  生成退款数据
            $backArr = [
                'order_id' => $orderId,
                'refund_no' => createOrderNumber('ZXTK', 6),
                'order_money' => $order['pay_price'],
                'back_money' => $moneyNormal + $moneyCar
            ];
            $back->save($backArr);

            return [
                'out_trade_no' => $order['ordernumber'],
                'total_fee' => $back->order_money,
                'refund_fee' => $back->back_money,
                'out_refund_no' => $back->refund_no
            ];
        }
    }

    /**
     * @param $orderNo
     * @param $refundNo
     * @return bool
     * @throws \think\exception\PDOException
     * @author zhenhong~
     * 退款成功回调逻辑
     */
    public function checkBackOrderInfo($orderNo, $refundNo)
    {
        $this->startTrans();
        try {
            //  查询订单信息
            $order = self::where('ordernumber', $orderNo)->field('id,u_id,a_id')->find();

            //  更新订单状态
            self::save(['status' => 7], ['ordernumber' => $orderNo]);

            //  更新退款表状态
            $back = new BackMoney();
            $back_info = $back->where(['refund_no' => $refundNo])->field('id,back_money')->find();
            $back->save(['status' => 2], ['id' => $back_info['id']]);


            //  减去对应商户账户的金钱
            $cash = new Cash();
            $cash->where('a_id', $order['a_id'])->setDec('wallet', $back_info['back_money']);

            //  判断此订单 是否存在取车订单
            $carOrder = new Getcarorder();
            $is_car_order = $carOrder->where('order_id', $order['id'])->value('id');
            if ($is_car_order) {
                $carOrder->save(['status' => 8], ['id' => $is_car_order]);
            }

            //  插入用户账单表
            $user_bill = [
                'u_id' => $order['u_id'],
                'a_id' => $order['a_id'],
                'price' => $back_info['back_money'],
                'lessorad' => 0,
                'content' => '退款' . $back_info['back_money'] . '元'
            ];
            $userBill = new Userbill();
            $userBill->save($user_bill);

            //  插入商户账单表
            $cash_bill = [
                'u_id' => $order['u_id'],
                'a_id' => $order['a_id'],
                'price' => $back_info['back_money'],
                'lessorad' => 1,
                'content' => '用户退款' . $back_info['back_money'] . '元'
            ];
            $cashBill = new Cashbill();
            $cashBill->save($cash_bill);
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * @param $id
     * @param $status
     * @return int
     * @author zhenhong~
     * 商户修改订单状态 为服务中-6 或 待评价-3
     */
    public function setStatusByOrderId($id, $status)
    {
        return self::where('id', $id)->setField('status', $status);
    }

    /**
     * @param $where
     * @param int $page
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 查询当前用户的订单列表
     */
    public function getByUserIdSelectOrder($where, $page = 1,$listnum=10)
    {

        $list['list'] = $this
                ->where($where)
                ->page($page, $listnum)
                ->order('ctime desc')
                ->select();

        $list['total'] = $this->where($where)->count();


        return $list;
    }

    /**
     * @param $orderNo
     * @return false|int
     * @author zhenhong~
     * 根据订单编号，取消订单
     * 这里需要判断，当前订单号，是否关联了上门取车订单
     */
    public function resetUserOrder($post)
    {
        $orderId = self::where('ordernumber', $post['ordernumber'])->value('id');

        $carOrder = new Getcarorder();

        $carOrderId = $carOrder->where('order_id', $orderId)->value('id');

        if ($carOrderId) {
            $carOrder->save(['status' => 7], ['id' => $carOrderId]);
        }

        return self::save([
            'status' => 5, 'deletordder' => $post['deletordder']
        ], [
            'ordernumber' => $post['ordernumber']
        ]);
    }

    /**
     * @param $orderNO
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 订单详细信息
     */
    public function getOrderDetailsByOrderNo($orderNO)
    {
        return $this->getOrderInfo($orderNO);
    }


    /**
     * @param $orderNo
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 根据订单号获取相关订单信息
     */
    protected function getOrderInfo($orderNo)
    {

        $order = self::get(['ordernumber' => $orderNo])->getData();

        return $order;
    }

    /**
     * @param $where
     * @param $page
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenhong~
     * 查询订单列表
     */
    public function selectOrder($where, $page)
    {

        $list['list'] = self::select(function ($query) use ($where, $page) {
            $query->where($where)->page($page, 10)->order('ctime desc');
        });
        $list['total'] = self::where($where)->count();

        return $list;
    }

    /**
     * @param $array
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 根据条件 ：车辆品牌、车辆车系、车辆车型、商户 匹配该商户对应商品
     */
    public static function getCommodityByCondition($array)
    {
        //  为变量赋初值
        $cashList = $commodityList = $plist = [];

        //  组装查询条件
        $where = [
            'A.b_id' => $array['b_id'],
            'A.t_id' => $array['t_id'],
            'A.m_id' => $array['m_id'],
            'A.a_id' => $array['a_id'],
        ];

        //  链表
        $join = [
            ['__BRAND__ B', 'B.id = A.brand', 'LEFT'],
            ['__PRODUCTCLASS__ P', 'P.id = A.productclass', 'LEFT']
        ];

        //  基本字段
        $field = "A.id,A.brand,A.title,A.ishot,A.nowprice,A.oldprice,A.describe,A.class,A.productclass,
        B.name brandName,P.name productName,P.description";

        //  商户基本字段
        $fieldCash = 'A.a_id,A.commodity_id,' . $field;

        //  按条件获取商户 商品列表数据
        $cashProduct = Commodityforcash::alias('A')->select(function ($query) use ($where, $join, $fieldCash) {
            $query->field($fieldCash)
                ->join($join)
                ->where($where)
                ->where('A.inventory', 'gt', 0)
                ->where('A.status', 'neq', 9);
        });

        foreach ($cashProduct as $objArr) {
            $cashList[] = $objArr->getData();
        }

        //  获取商户 已添加的平台商品id
        $ids = array_column($cashList, 'commodity_id');

        //  获取商户未添加的平台商品
        $commodity = Commodity::alias('A')->select(function ($query) use ($ids, $join, $field) {
            $query->field($field)
                ->join($join)
                ->whereNotIn('A.id', $ids)
                ->where('A.inventory', 'gt', 0)
                ->where('A.status', 'neq', 9);
        });

        foreach ($commodity as $commoditys) {
            $commodityList[] = $commoditys->getData();
        }

        //  商户 + 平台商品
        $allProduct = array_merge($cashList, $commodityList);

        //  将数组 按 class 字段分组
        foreach ($allProduct as $v) {
            $plist[$v['class']][] = $v;
        }

        return $plist;
    }

    /**
     * @param $array
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 根据商户id 组装机油数据
     */
    public static function getOilByCondition($array)
    {
        //  为变量赋初值
        $cashList = $oilList = $plist = [];

        //  链表
        $join = [
            ['__BRAND__ B', 'B.id = A.brand', 'LEFT']
        ];

        //  平台机油字段
        $field = "A.id,A.brand,A.title,A.sfcation,A.ishot,A.nowprice,A.oldprice,A.class,B.name brandName,B.head_pic brandPic,B.describtion";

        //  商户 机油字段
        $fieldCash = 'A.a_id,A.machineoil_id,' . $field;

        $cashOil = Machineoilforcash::alias('A')->select(function ($query) use ($array, $join, $fieldCash) {
            $query->join($join)
                ->field($fieldCash)
                ->where('A.a_id', $array['a_id'])
                ->where('A.inventory', 'gt', 0)
                ->where('A.status', 'neq', 9);
        });

        foreach ($cashOil as $objArr) {
            $cashList[] = $objArr->getData();
        }

        //  获取商户 已添加的平台机油id
        $ids = array_column($cashList, 'machineoil_id');

        //  获取商户未添加的平台商品
        $oil = Machineoil::alias('A')->select(function ($query) use ($ids, $join, $field) {
            $query->join($join)
                ->field($field)
                ->whereNotIn('A.id', $ids)
                ->where('A.inventory', 'gt', 0)
                ->where('A.status', 'neq', 9);
        });

        foreach ($oil as $oils) {
            $oilList[] = $oils->getData();
        }

        //  商户机油 + 平台机油
        $allProduct = array_merge($cashList, $oilList);

        //  将数组 按 class 字段分组
        foreach ($allProduct as $v) {
            $plist[$v['class']][] = $v;
        }

        return $plist;
    }


    /**
     * @param $array
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author zhenHong~
     * 根据商户id以及用户车辆信息数据，获取商户-商品页面数据
     */
    public static function getAllByCondition($array)
    {
        //  获取机油 和 商品数据
        $commodity = self::getCommodityByCondition($array);
        $oil = self::getOilByCondition($array);

        //  查询商户 工时费、是否支持预约到店、是否支持上门服务
        $cash = Db::name('Cash')->where('a_id', $array['a_id'])->field('hour_free,break_scale,support_reserve,gohome')->find();

        //  组装数组 将原厂 与 国际大品牌分组
        $all = [
            //  对应商户的工时费
            'hour_free' => $cash['hour_free'],
            //  预约到店
            'support_reserve' => $cash['support_reserve'],
            //  上门服务
            'gohome' => $cash['gohome'],
            //  退还服务费(上门)比例
            'break_scale' => $cash['break_scale'],
            //  国际大厂配件
            'inter' => [
                'inter_oil' => setGroupByArray($oil, 1),
                'inter_commodity' => setGroupByArray($commodity, 1, true),
            ],
            //  原厂配件
            'original' => [
                'original_oil' => setGroupByArray($oil, 2),
                'original_commodity' => setGroupByArray($commodity, 2, true)
            ],
        ];
        return $all;
    }

    /*
    * Notes: 金额统计
    * Create Date: 2018/10/16
    * Create Time: 下午3:50
    * Create by :张福来
    * param :
    */
    public function orderMoney($wh, $group)
    {
        $sql = $this
            ->field("pay_price,status,ctime,c_id,FROM_UNIXTIME(ctime,'%Y-%m-%d %H:%i:%s') my_date,FROM_UNIXTIME(ctime,$group) group_time")
            ->buildSql();
        $result["data"] = Db::table("{$sql}")
            ->alias("a")
            ->field("a.pay_price price,SUM(a.pay_price) totalprice,a.group_time")
            ->where($wh)
            ->group("a.group_time")
            ->select();
        $result["alltotal"] = $this
            ->alias("a")
            ->field("SUM(a.pay_price) alltotal")
            ->where($wh)
            ->find();
        return $result;
    }
}